import { Component, ChangeDetectorRef, ChangeDetectionStrategy, Input } from '@angular/core';

import * as _ from 'lodash';
import { SubIndustryModel } from '../../templates/subIndustry/subIndustry.model';
import { CompanyRiskRatingService } from '../../companyRiskRating.service';
import { HttpClient } from '@angular/common/http';
import { UtilsService } from '../../../../../../shared/services/utils.service';
import { Observable } from 'rxjs/Observable';
import { UniverseBenchmarkModel, SubIndustryBenchmarkModel, IndustryBenchmarkModel } from '../../models/riskBenchmark.model';
import { RiskExposureModel } from '../../models/riskExposure.model';
import { ChartExposureModel } from '../../../../../../shared/models/chartExposure.model';
import { ClusterService } from '../../../../riskCluster/cluster.service';

/**
 * Company sub industry summary component
 *
 * Author: Sorin Spiru
 * Date: 16.01.2018
 */
@Component({
    selector: 'subindustry-risk-rating',
    templateUrl: '../../templates/subIndustry/subIndustry.component.html',
    styleUrls: [
        '../../../company.component.scss',
        '../../companyRiskRating.component.scss',
        '../../templates/subIndustry/subIndustry.component.scss'
    ],
    providers: [UtilsService],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class SubIndustrySummaryComponent extends SubIndustryModel {

    public formatRank = UtilsService.formatRank;
    public company;
    public ratingDistributionChartColors: { color: string; alpha: number; }[];
    @Input() displayType = 'distribution';
    @Input() isCore = false;

    constructor(
        private cdRef: ChangeDetectorRef,
        private riskService: CompanyRiskRatingService,
        private clusterService: ClusterService) {
        super(cdRef);
        this.primaryName = "Universe";
        this.secondaryName = "Subindustry";
        this.ratingDistributionChartColors = [
            { color: "#CCCCCC", alpha: 1 },
            { color: "#175f96", alpha: 0.5 },
            { color: "#175f96", alpha: 1 }
        ];
    }

    ngOnInit() {
        this.maxManagement = 100;
        this.maxExposure = 100;
        this.displayRatingDistribution = true;
        this.loaded = new Promise<void>((resolve, reject) => {
            this.riskService.company.subscribe(company => {
                this.company = company;
                this.subIndustryAverageExposure = company.subIndustryAverageExposure;
                this.subIndustryAverageManagement = company.subIndustryAverageManagement;
                this.currentCompany = company.id;
                this.currentCompanyName = company.companyName;
                this.companyClusterCode = company.assessmentCode;
                this.cdRef.markForCheck();
                this.clusterService.company.subscribe(clusters => {
                    this.riskClusters = clusters;
                    let promises: Array<any> = [
                        this.riskService.getCompanyUniverseBenchmark(company.id),
                        this.riskService.getCompanySubIndustryBenchmark(company.id),
                        this.riskService.getCompanySubIndustryExposure(company.id),
                        this.riskService.getCompanyIndustryBenchmark(company.id)
                    ];

                    if (this.displayType == 'scatter')
                        promises.push(this.riskService.getUniverseExposure());

                    Observable.forkJoin(promises).subscribe(data => {
                        this.universe = data[0] as UniverseBenchmarkModel;
                        this.subIndustry = data[1] as SubIndustryBenchmarkModel;
                        this.scatter = data[2] as RiskExposureModel[];
                        this.industry = data[3] as IndustryBenchmarkModel;
                        if (this.displayType == 'scatter')
                            this.universeExposure = data[4] as RiskExposureModel[];
                        else
                            this.universeExposure = [];

                        this.cdRef.markForCheck();

                        // prepare data
                        let universeData = UtilsService.aggregateDataByRiskCluster(this.riskClusters, this.universe.chartData, 'universe');
                        let subIndustryData = UtilsService.aggregateDataByRiskCluster(this.riskClusters, this.subIndustry.chartData, 'subIndustry');
                        let industryData = UtilsService.aggregateDataByRiskCluster(this.riskClusters, this.industry.chartData, 'industry');

                        // merge data sets by riskCluster
                        this.benchmarkData = _(universeData)
                            .concat(industryData)
                            .concat(subIndustryData)
                            .groupBy('riskCluster')
                            .map(_.spread(_.merge))
                            .value();

                        //scatter chart data
                        let companyBullet: ChartExposureModel;
                        let scatterResult: ChartExposureModel[] = [];
                        this.scatter.forEach(subGroupCompany => {
                            companyBullet = new ChartExposureModel(
                                subGroupCompany.management,
                                subGroupCompany.exposure,
                                null,
                                subGroupCompany.companyName
                            );

                            this.subIndustry.peersList.forEach(peer => {
                                if (peer.companyId == subGroupCompany.companyId) {
                                    companyBullet.peerPosition = peer.rank;
                                    if (subGroupCompany.companyId == company.id) {
                                        companyBullet.currentX = companyBullet.X;
                                        companyBullet.currentY = companyBullet.Y;
                                    }
                                    else {
                                        companyBullet.peerX = companyBullet.X;
                                        companyBullet.peerY = companyBullet.Y;
                                    }
                                    return;
                                }
                            });

                            scatterResult.push(companyBullet);
                        });
                        this.universeExposure.forEach(peer => {
                            if (peer.companyId != company.id) {
                                let universe = new ChartExposureModel(undefined, undefined)
                                universe.peerX = peer.exposure;
                                universe.peerY = peer.management;
                                universe.name = peer.companyName;
                                scatterResult.push(universe);
                            }
                        });
                        this.exposureData = scatterResult;

                        this.cdRef.markForCheck();
                        resolve();
                    });
                });
            });
        });
    }
}